<?php
/**
 * 数据库连接类
 *
 * @package		Hooloo framework
 * @author 		Bill
 * @copyright 	Hooloo Co.,Ltd
 * @version		1.0
 * @release		2017.05.08
 */
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Database {
	protected $_db_handle;
	protected $_result;
	
	//连接数据库
	public function connect($address, $username, $password, $db_name) {
		$this->_db_handle = new mysqli($address, $username, $password, $db_name);
		$this->_db_handle->set_charset('utf8');
	}
	
	//自定义SQL查询语句
	public function query($sql) {
		$runtime1 = microtime(true);
		$this->_result = $this->_db_handle->query($sql);
		if (DEVELOPMENT_ENVIRONMENT && $this->_db_handle->error) {
			printf("出错了：%s", $this->_db_handle->error . "<br />");
			printf($sql);
			exit;
		}
		return $this;
	}
	
	//返回单条数据
	public function row_array() {
		if (false !== $this->_result) {
			$result = $this->_result->fetch_assoc();
			$this->_result->free();
		} else {
			$result = array();
		}
		return $result;
	}
	
	//返回多条数据
	public function result_array() {
		$result = array();
		if (false !== $this->_result) {
			while($row = $this->_result->fetch_assoc()) {
				$result[] = $row;
			}
			$this->_result->free();
		}
		return $result;
	}
	
	//返回最后插入id
	public function insert_id() {
		$result = $this->_db_handle->insert_id;
		return $result;
	}
	
	//返回影响函数
	public function affected_rows() {
		$result = $this->_db_handle->affected_rows;
		return $result;
	}
	
	//开启事务
	public function trans_begin() {
		mysqli_query($this->_db_handle, "SET AUTOCOMMIT = 0");//设置为不自动提交，因为MYSQL默认立即执行
		mysqli_begin_transaction($this->_db_handle);//开始事务定义
	}
	
	//回滚事务
	public function trans_rollback() {
		mysqli_query($this->_db_handle, "ROLLBACK");//判断当执行失败时回滚
	}
	
	//提交事务
	public function trans_commit() {
		mysqli_commit($this->_db_handle);//执行事务
	}
	
	//关闭数据库连接
	public function close() {
		$this->_db_handle->close();
	}
	
	//返回MySql版本
	public function getserver_info(){
		return mysqli_get_server_info($this->_db_handle);
	}
}
